package com.sangeng.filter;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.sangeng.domain.entity.user.LoginUser;
import com.sangeng.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.sangeng.constant.RedisConst.USER_LOGIN_INFO;


@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("TOKEN");
        if(token == null){//token不存在，返回错误信息
            //放行
            filterChain.doFilter(request,response);//SecurityConfig类中的.antMatchers("/user/login").anonymous()配置，发现是登录操作，则让其继续执行后续的操作
            return;
        }
        //解析token
        Claims claims = null;
        try {
            claims = JwtUtil.parseJwt(token);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token解析失败");
        }
        Long userId = claims.get("userId", Long.class);
        //从redis中获取用户信息
        String userInfoStr = stringRedisTemplate.opsForValue().get(USER_LOGIN_INFO + userId);
        if(StrUtil.isBlank(userInfoStr)){
            throw new RuntimeException("用户未登录");
        }
        LoginUser loginUser = JSON.parseObject(userInfoStr, LoginUser.class);
        //把用户信息存入SecurityContextHolder
        //获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request,response);
    }
}
